package com.zhouchao.mvp2.login;

import android.os.Handler;
import android.util.Log;

import com.zhouchao.mvp2.entity.User;
import com.zhouchao.mvp2.mvp.BasePresenter;

/**
 * 描述：
 * zhougan
 * 2019/2/28
 **/
public class LoginPresenter extends BasePresenter<LoginContract.ILoginView> implements LoginContract.ILoginPresenter {
    private static final String TAG = ">>>LoginPresenter";
    private LoginContract.ILoginModel loginModel;
    private User user;
    private Handler handler;
    public LoginPresenter() {
        loginModel=new LoginModel();
        handler=new Handler();
    }


    @Override
    public void login(String name, String pwd) {
        if(user==null){
            user=new User(name,pwd);
        }else{
            user.setName(name);
            user.setPwd(pwd);
        }

        String invalidate = loginModel.invalidate(user);
        //验证失败
        if(!LoginModel.INVALIDATE_SUCCESS.equalsIgnoreCase(invalidate)){
            if(isAttach()){
                getView().onLogionFailure(invalidate);
            }
        }else{
            //验证成功
            if(isAttach()){
                setProgressVisibility(true);
                loginModel.login(user, new LoginContract.ILoginModel.Callback() {
                    @Override
                    public void onLoginSuccess() {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if(isAttach()){
                                    setProgressVisibility(false);
                                    getView().onLoginSuccess();
                                }else{
                                    Log.i(TAG, "run: 销毁了View");
                                }

                            }
                        });
                    }

                    @Override
                    public void onLoginFailure(final String msg) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if(isAttach()){
                                    setProgressVisibility(false);
                                    getView().onLogionFailure(msg);
                                }else{
                                    Log.i(TAG, "run: 销毁了View");
                                }

                            }
                        });
                    }
                });
            }


        }

    }

    @Override
    public void setProgressVisibility(Boolean visibility) {
        if(isAttach()){
            getView().onProgressBarShow(visibility);
        }
    }
}
